package com.example.test.test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CHMDemo {


    public static ConcurrentHashMap<String ,Long> map  = new ConcurrentHashMap<>();


    public static void process(Path file){
        try (Scanner in = new Scanner(file)){
            while (in.hasNext()){
                String word = in.next();
                map.merge(word,1L,Long::sum);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Set<Path> descendants(Path rootDir){
        try (Stream<Path> entries = Files.walk(rootDir)){
            return entries.collect(Collectors.toSet());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int processors = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = Executors.newFixedThreadPool(processors);
        Path path = Paths.get(",");
        for (Path p:descendants(path)) {
            if (p.getFileName().toString().endsWith(".java"))
                executorService.execute(()->process(p));
        }
        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.MINUTES);
        map.forEach((k,v)->{
            if(v>=10)
                System.out.println(k+"occurs"+v+"times");
        });
    }
}
